package com.itcast.rpc.server.zk;

import com.itcast.common.annotation.RpcService;
import com.itcast.common.utils.IpUtil;
import com.itcast.common.utils.SpringBeanFactory;
import com.itcast.rpc.server.config.RpcServerConfiguration;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Zookeeper服务连接注册管理
 */
@Component
public class ServicePushManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServicePushManager.class);

    @Autowired
    private ZKit zKit;

    @Autowired
    private RpcServerConfiguration configuration;

    /**
     * 服务注册接口
     */
    public void registerIntoZK() {
        Map<String, Object> beanListByAnnotationClass =
                SpringBeanFactory.getBeanListByAnnotationClass(RpcService.class);
        if (!MapUtils.isEmpty(beanListByAnnotationClass)){
            // 根节点创建
            zKit.createRootNode();
            for (Object bean : beanListByAnnotationClass.values()) {
                RpcService annotation = bean.getClass().getAnnotation(RpcService.class);
                Class<?> cls = annotation.cls();
                String serviceName = cls.getName();

                // 创建节点
                zKit.createPersistentNode(serviceName);

                String serviceAddress = IpUtil.getRealIp() +
                        ":"+configuration.getServerPort()+
                        ":"+configuration.getNetworkPort();
                zKit.createNode(serviceName+"/"+serviceAddress);
            }
        }
    }

}
